﻿using System;
using UnityEngine;
using System.Collections;

namespace HNet
{
    //负责网络数据读取分发
    public class NetCoroutinue : MonoSingleton<NetCoroutinue>
    {
        public bool Running = false;

        private bool _isInited = false;

        private bool _SetLocalHost = false;

        private Action<byte[]> _sendLocalServer;

        public MessageProcessing Processing;

        //用于最终取到的消息
        private SwitchQueue<byte[]> BytesQueue = new SwitchQueue<byte[]>(128);

        public void Init()
        {
            DontDestroyOnLoad(gameObject);
        }

        public void Refresh()
        {
            //保证初始化一次
            if (_isInited == false)
            {
                Init();
                _isInited = true;
            }
            _SetLocalHost = false;
            Processing = new MessageProcessing();
            BytesQueue.Clear();
            Running = true;
            StartCoroutine(PickUpdate());
        }

        public void Close()
        {
            BytesQueue.Clear();
            StopAllCoroutines();
            Running = false;
            //Destroy(gameObject);
        }

        public void InputBytes(byte[] bytes)
        {
            BytesQueue.Push(bytes);
        }

        // 这里耦合有点高

        public void SendBytesMeth(int[] receiver, string methName, byte[] param)
        {
            Message msg = new Message();

            RemoteMethod.GenerateBytesMeth(methName, param, ref msg);

            msg.Sender = (int)NetController.Instance.Client.Conv;
            msg.Receiver = receiver;
            byte[] bytes = ProtocolBuffer.Serialize<Message>(msg);
            SendToServer(bytes);
        }

        private void SendToServer(byte[] bytes)
        {
            if (_SetLocalHost == false)
            {
                NetController.Instance.Client.Send(bytes);
            }
            else
            {
                _sendLocalServer(bytes);
            }
        }

        public void SetLocalHost(Action<byte[]> sendLocalServer)
        {
            _SetLocalHost = true;
            _sendLocalServer = sendLocalServer;
        }

        //直接处理
        public void LocalHostDistribute(byte[] bytes)
        {
            Message msg = ProtocolBuffer.DeSerialize<Message>(bytes);

            Processing.Distribute(msg);
        }

        //解析数据
        private IEnumerator PickUpdate()
        {
            while (Running)
            {
                while (!BytesQueue.Empty())
                {
                    var buf = BytesQueue.Pop();
                    Message msg = ProtocolBuffer.DeSerialize<Message>(buf);

                    Processing.Distribute(msg);

                    string str = System.Text.Encoding.UTF8.GetString(msg.DataList[0]);
                    string time = System.Text.Encoding.UTF8.GetString(msg.DataList[1]);

                    NetLog.C("收到来自" + msg.Sender + "数据(" + buf.Length + "):" + str + " ,时间：" + time);
                }

                yield return 0;
            }
        }
    }
}